<template>
    <div class="home" :class="{ mini: isShowBar }">
        <Header v-if="!isShowBar" title="销售演示" no-bottom-border left-arrow :custom-left-click="back" />
        <div v-else class="van-safe-area-top" />
        <div class="city-select">
            <div class="field" @click="isShowCitySelecter = true">
                <div class="field-label">
                    <label>{{ selectCity?.name }}</label>
                </div>
                <div class="field-input">
                    <span class="placeholder">请输入城市名称搜索</span>
                </div>
            </div>
        </div>
        <div class="tab-strategy">
            <van-tabs v-model:active="tabIndex" class="fe-tab" @change="changeScene">
                <van-tab v-for="(item, index) in tabList" :key="'vantab' + index" :title="item.name" :name="item.value">
                </van-tab>
            </van-tabs>
        </div>
        <div class="content">
            <coverage-distribution
                v-show="!isLoading" ref="coverageRef" :scene="tabIndex" :table-data="tableData"
                :has-no-data="hasNoData" :city="selectCity && selectCity.id || ''"
            />
            <div v-if="isLoading" class="loading">
                <van-loading type="spinner" />
            </div>
            <cph-calc v-show="tabIndex === 1" ref="cphCalcRef" @focus="onFocus" @blur="onBlur" />
        </div>
        <div ref="contentRef" class="bottom" :class="{ mini: isShowBar }">
            <div :class="!selectCity?.name && 'disabled'" @click="toProducts">
                选择软产品
            </div>
        </div>
    </div>
    <city-selecter :show-action="isShowCitySelecter" @confirm="onConfirm" @close="isShowCitySelecter = false">
    </city-selecter>
    <xctabbar v-if="isShowBar" :selected="1"></xctabbar>
</template>

<script lang="ts" setup name="home">
import { ref, onActivated } from 'vue';
import { useRouter,useRoute } from 'vue-router';
import CphCalc, { TYPE } from '@/components/CphCalc/index.vue';
import CoverageDistribution from './components/CoverageDistribution.vue';
import Header from '@/components/Header/index.vue';
import { getHomePageMediaCoverage } from '@/api/home';
import { onMounted } from 'vue';
import {
    Loading as VanLoading, Toast, Tabs as VanTabs,
    Tab as VanTab,
} from 'vant';
import { CoverNumberItemModel, GeolocationModule } from './home.module';
import CitySelecter from '@/components/CitySelecter/index.vue';
import { TreeChildModel } from '@/components/CityAreaSelecter/city.module';
import { CphTableItemModel } from '../products/brandBreakout/breakout.module';
import { handleMediaResource, isWx } from '@/utils/index';
import { getCityTreeData } from '@/api/common';
import { store } from '@/store';
import { PositionModel } from '@/components/CitySelecter/citySelecter.module';
import xctabbar from '@/components/XCTabbar/index.vue';
import { NativePath, openUrl, getGeoLocationOnReady, posData } from '@/utils/native';
import { clearLoading, showLoading } from '@/api';
import { reject } from 'lodash';
import { computed } from 'vue';

const isShowBar = ref(false);

isWx().then(type => {
    if (type === 'mini-wx') {
        document.title = '软产品';
        isShowBar.value = true;
    }
}).catch(e => 0);
const router = useRouter();
const isLoading = ref(false);
const cphCalcRef = ref<TYPE>();
const tableData = ref<CoverNumberItemModel[]>();
const hasNoData = ref(false);
const isShowCitySelecter = ref(false);
const selectCity = ref<TreeChildModel>();// 默认当前用户所在城市
const tabIndex = ref(1);
const tabList = ref([{ name: '社区场景', value: 1 }, { name: '商务场景', value: 2 }]);
const coverageRef = ref<{ initMediaType:() => void }>();
const citySearchList = ref<TreeChildModel[]>();

const contentRef = ref<HTMLElement>();
const onFocus = () => {
    if (contentRef.value) {
        contentRef.value.style.display = 'none';
    }
};
const onBlur = () => {
    if (contentRef.value) {
        contentRef.value.style.display = 'block';
        window.scrollTo(0, 0);
    }
};

const back = async () => {
    await openUrl({
        url: NativePath.CLOSE,
        params: {}
    });
};

const toProducts = async () => {
    if (!selectCity.value?.name) {
        // Toast.fail('请选择城市');
        return;
    }
    // 计算最优媒体类型
    if (cphCalcRef.value) {
        let mediaType = 1;
        // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
        const tableList = cphCalcRef.value?.tableList as CphTableItemModel[];
        store.commit('app/setHomeCphTableList', tableList);
        if (tableList.length && tableList[2]) {
            const cphRow: CphTableItemModel = tableList[2];
            const min = Math.min(cphRow.num1, cphRow.num2);// 最优媒体类型取智能屏和LCD中最小的，优先智能屏
            if (cphRow.num1 === min) {
                mediaType = 1;
            } else {
                mediaType = 2;
            }
        }
        store.commit('app/setOptimalMediaType', mediaType);
    }
    await router.push({
        name: 'products',
    });
};

const initData = async () => {
    isLoading.value = true;
    showLoading();
    try {
        const res = await getHomePageMediaCoverage({
            cityCodes: [selectCity.value?.id || ''],
            businessScenario: tabIndex.value
        });
        isLoading.value = false;
        if (!res) {
            hasNoData.value = true;
            return;
        }
        hasNoData.value = false;
        tableData.value = tabIndex.value === 1 ? handleMediaResource(res) : handleMediaResource(res).filter(item => item.type !== 5);
    } catch (error) {
        hasNoData.value = true;
        isLoading.value = false;
    } finally {
        clearLoading();
    }
};

const changeScene = async (value: number) => {
    tabIndex.value = value;
    coverageRef.value?.initMediaType();
    await initData();
};

// 获取城市列表数据
const initCityData = async () => {
    const cityList: TreeChildModel[] = await getCityTreeData(2) as unknown as TreeChildModel[];
    const cityAllList = cityList.map((item: TreeChildModel) => item.children);
    citySearchList.value = cityAllList.flat() as unknown as TreeChildModel[];
};

// 获取当前城市
const getLocationCity = async () => {
    Toast.loading({
        message: '正在定位中....',
        forbidClick: true,
        duration: 0,
    });
    const pos: posData | unknown = await getGeoLocationOnReady().catch(() => undefined);
    return new Promise((resolve) => {
        if (pos && pos.city) {
            Toast.clear();
            resolve(pos);
        } else {
            try {
                // eslint-disable-next-line
                const geolocation: GeolocationModule = new BMap.Geolocation();
                geolocation.getCurrentPosition((currentPositionData: PositionModel) => {
                    Toast.clear();
                    !!currentPositionData ? resolve(currentPositionData) : reject(undefined);
                });
            } catch (err) {
                Toast.clear();
                console.log(err);
                reject(undefined);
            }
        }
    });
};

const saveCity = computed(() => store.state.app.home.selectCity);
// 初始化城市选项数据
const initSelectCity = async (value?: TreeChildModel) => {
    let cityInfo;
    if (!!value) {
        cityInfo = value;
    } else if (!!saveCity.value && saveCity.value.id) {
        cityInfo = saveCity.value;
    } else {
        await initCityData();
        const pos: PositionModel = await getLocationCity().catch(()=>undefined) as PositionModel;
        if(pos){
            cityInfo = (citySearchList.value || []).filter((city: TreeChildModel) => {
                return city.name === (pos.city || pos.address.city);
            })[0];
        }else{
            Toast.fail({
                duration: 3000,
                forbidClick: true,
                closeOnClick: true,
                message: '获取定位失败！',
            });
        }
    }
    selectCity.value = cityInfo;
    cityInfo && store.commit('app/setHomeSelectCity', cityInfo);
};


const onConfirm = async (value: TreeChildModel) => {
    // selectCity.value = value;
    await initSelectCity(value);
    isShowCitySelecter.value = false;
    await initData();
};

onActivated(() => {
    isWx().then(type => {
        if (type === 'wx') {
            isShowBar.value = true;
        }
    }).catch(e => 0);
});

const route = useRoute();
onMounted(async () => {
    const productCode = route.query.productCode;
    store.commit('app/setProductCode', productCode||'');
    await initSelectCity();
    await initData();
});
</script>

<style lang="scss" scoped>
.home {
    background: #f4f4f4;
    width: 100%;
    display: flex;
    flex-direction: column;
    height: 100vh;

    &.mini {
        overflow: hidden;
        box-sizing: border-box;
        height: calc(100vh - 50px);
        min-height: calc(95vh - 50px);
    }

    .city-select {
        padding: 8px 12px;
        background: #ffffff;

        .field {
            height: 36px;
            background: #f8f8f8;
            border-radius: 6px;
            display: flex;
            align-items: center;

            .field-label {
                height: 20px;
                // font-family: PingFangSC-Medium;
                font-weight: 600;
                font-size: 14px;
                color: #333333;
                position: relative;
                padding: 2px 12px 0;
            }

            .field-label::after {
                content: "";
                display: inline-block;
                position: absolute;
                width: 1px;
                height: 12px;
                opacity: 0.39;
                background: #bfbfbf;
                right: 0;
                top: 4px;
            }

            .field-input {
                margin-left: 12px;
                flex: 1;

                .placeholder {
                    font-weight: 400;
                    font-size: 14px;
                    color: #d2d2d2;
                }
            }
        }
    }

    .tab-strategy {
        box-sizing: border-box;
        background: #fff;
        // border-bottom: 0.5px solid #eeeeee;
    }

    .content {
        overflow: auto;
        flex: 1;
        padding: 12px;

        .loading {
            background: #ffffff;
            height: 200px;
            margin-bottom: 12px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }

    .bottom {
        $height: var(constant(safe-area-inset-bottom), env(safe-area-inset-bottom));

        width: 100%;
        // height: $height;
        background: #ffffff;
        box-shadow: 0 2px 10px 0 #00000014;
        padding: 6px 12px 0;
        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);
        overflow: hidden;
        box-sizing: border-box;

        &.mini {
            margin-bottom: $height + 50;
        }

        div {
            height: 38px;
            line-height: 38px;
            background: #e60044;
            border-radius: 6px;
            // font-family: PingFangSC-Medium;
            font-weight: 600;
            font-size: 14px;
            color: #ffffff;
            text-align: center;
            margin-bottom: 8px;
        }

        .disabled {
            background: #f06690;
        }
    }
}
</style>
